using Microsoft.Web.WebView2.Core;
using MultiAgentsServer.Scripts.Shared;
using MultiAgentsShared;
using static MultiAgentsClient.Manager.MessageWebviewOperator;

namespace MultiAgentsClient.Presentation.Component;

public sealed partial class MessageWebview : UserControl
{
    private readonly IEventBus eventBus;

    public MessageWebview()
    {
        InitializeComponent();

        eventBus = EventBus.Instance;

        eventBus.Subscribe<LoadMessageWebviewPageCommand>(cmd => LoadWebviewPage(cmd.Path));
        eventBus.Subscribe<ExecuteMessageWebviewCommand>(cmd => ExecuteJavaScript(cmd.JSCode));

        LoadWebviewPage(FileConsts.MessagePageFileName);
    }

    public void LoadWebviewPage(string path)
    {
        try
        {
            DispatcherQueue.TryEnqueue(async () =>
            {
#pragma warning disable Uno0001
                await MessageWebviewComponent.EnsureCoreWebView2Async();
                string fullFilePath = Path.GetFullPath(path);
                MessageWebviewComponent.Source = new Uri(fullFilePath);

                MessageWebviewComponent.WebMessageReceived -= OnWebMessageReceived;
                MessageWebviewComponent.WebMessageReceived += OnWebMessageReceived;
#pragma warning restore Uno0001
            });
        }
        catch (Exception ex)
        {
            Debug.LogError($"Html Error: {ex.Message}");
        }
    }

    private void OnWebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
    {
        eventBus.Publish(new MessageWebViewReceiveMessageCommand(sender, e.TryGetWebMessageAsString()));
    }

    public void ExecuteJavaScript(string jsCode)
    {
        try
        {
            DispatcherQueue.TryEnqueue(async () =>
            {
#pragma warning disable Uno0001
                await MessageWebviewComponent.EnsureCoreWebView2Async();

                await MessageWebviewComponent.ExecuteScriptAsync(jsCode);
#pragma warning restore Uno0001
            });
        }
        catch (Exception ex)
        {
            Debug.LogError($"JavaScript Error: {ex.Message}");
        }
    }
}
